import userService from "@/api/user/index";
import { getToken, setToken, removeToken } from "@/utils/auth";
import { resetRouter } from "@/router";

const getDefaultState = () => {
  return {
    token: getToken("token"), // 登录用户的token
    name: getToken("account"), // 登录用户名
    status: false, // 用户状态有无更改 可改变路由
    userInfo: {
      account: '',
      password: '' } // 存储登录的用户名和密码
  };
};

const state = getDefaultState();

const mutations = {
  RESET_STATE: state => {
    Object.assign(state, getDefaultState());
  },
  SET_STATUS: (state, status) => {
    state.status = status;
  },
  SET_USERINFO: (state, status) => {
    state.userInfo = status;
  }
};

const actions = {
  login({ commit }, userInfo) {
    let infoo = JSON.stringify(userInfo);
    commit("SET_USERINFO", userInfo);
    setToken("userInfo", infoo);
    const { account, password } = userInfo;
    return new Promise((resolve, reject) => {
      // let name = account.trim()
      // if (name === 'ywadmin' && password) {
      //   setToken("token", 'hasywtoken');
      //   setToken("userId", 1);
      //   setToken("account", 'ywadmin');
      //   resolve();
      // } else {
      //   reject();
      // }
      userService
        .login({ omUserName: account.trim(), password: password })
        .then(response => {
          // const data = response.data.loginUser;
          if (response.code === 1) {
            const data = response.data;
            // console.log(response)
            setToken("token", data.token);
            setToken("account", data.omUserName);
            setToken("userId", data.omUserId);
            // setToken("companyMark", data.companyMark);
            resolve();
          } else {
            reject(response.msg);
          }
        })
        .catch(error => {
          reject(error);
        });
    });
  },

  // user logout
  logout({ commit, state }) {
    return new Promise((resolve, reject) => {
      // 删除全部本地缓存
      sessionStorage.clear();
      resetRouter(); // 重置路由
      commit("RESET_STATE"); // 重置用户数据
      resolve();
    });
  },

  // remove token
  resetToken({ commit }) {
    return new Promise(resolve => {
      removeToken("token"); // must remove  token  first
      commit("RESET_STATE");
      resolve();
    });
  }
};

export default {
  namespaced: true,
  state,
  mutations,
  actions
};
